<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/bootstrap-table.min.css">
    <link rel="stylesheet" href="/css/pub.css">
    <link rel="stylesheet" href="/css/order.css">
    <link rel="stylesheet" href="/css/font-awesome-all.min.css">
    <style>
        #orderTable {
            margin-top: 20px;
        }

        .nav-tabs {
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <ul class="nav nav-tabs" id="orderTabs" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="query-tab" data-bs-toggle="tab" data-bs-target="#query-tab-pane"
                type="button" role="tab" aria-controls="query-tab-pane" aria-selected="true">查询</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="sync-tab" data-bs-toggle="tab" data-bs-target="#sync-tab-pane" type="button"
                role="tab" aria-controls="sync-tab-pane" aria-selected="false">MQTT同步入库</button>
        </li>
    </ul>

    <div class="tab-content" id="orderTabsContent">
        <div class="tab-pane fade show active" id="query-tab-pane" role="tabpanel" aria-labelledby="query-tab"
            tabindex="0">
            <div class="query-area mb-3">
                <div class="row g-3">
                    <div class="one-row-input-zone">
                        <label class="form-label">分类代码</label>
                        <input type="text" class="form-control" id="queryCategoryCode">
                    </div>
                    <div class="one-row-input-zone">
                        <label class="form-label">品牌</label>
                        <input type="text" class="form-control" id="queryBrand">
                    </div>
                    <div class="one-row-input-zone">
                        <label class="form-label">区域</label>
                        <input type="text" class="form-control" id="queryZone">
                    </div>
                </div>
            </div>
            <div>
                <button class="btn btn-primary" onclick="queryOrders()">查询</button>
                <button class="btn btn-success" onclick="showAddForm()">添加订单</button>
            </div>



            <div id="dataView">
                <table id="orderTable" data-ajax="ajaxQueryPage" data-toggle="table" data-pagination="true"
                    data-side-pagination="server" data-page-size="10" data-page-list="[10, 25, 50, 100]"
                    data-search="false">
                    <thead>
                        <tr>
                            <th data-field="id" data-sortable="true">ID</th>
                            <th data-field="eventTime" data-sortable="true">事件时间</th>
                            <th data-field="productId" data-sortable="true">产品ID</th>
                            <th data-field="categoryCode" data-sortable="true">分类代码</th>
                            <th data-field="brand" data-sortable="true">品牌</th>
                            <th data-field="price" data-sortable="true">价格</th>
                            <th data-field="zoneName" data-sortable="true">区域</th>
                            <th data-field="operate" data-formatter="operateFormatter">操作</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>

        <div class="tab-pane fade" id="sync-tab-pane" role="tabpanel" aria-labelledby="sync-tab" tabindex="0">
            <div class="sync-area mt-3">
                <div class="row">
                    <div class="col-md-6">
                        <h5>发送订单到阿耳忒弥斯</h5>
                        <button class="btn btn-primary mb-3" id="startMqttBtn" onclick="onClickStartMqtt()"><i
                                class="fa-solid fa-share-nodes"></i>发送</button>
                        <button class="btn btn-danger mb-3" id="releaseLockBtn" onclick="onClickReleaseLock()"><i
                                class="fa-solid fa-unlock"></i>释放锁</button>
                        <button class="btn btn-primary mb-3" id="restartWebsocket" disabled
                            onclick="onClickRestartWebsocket()"><i class="fa-solid fa-plug"></i>重连Socket</button>
                        <div class="message-container  ws-messages p-3 border rounded">
                            <div id="wsMessages" class="message-body"></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h5>接收阿耳忒弥斯订单,并写入数据库</h5>
                        <button class="btn btn-success mb-3 ms-2" id="startMqttSinkBtn" onclick="startMqttSink()"><i
                                class="fa-solid fa-circle-play"></i>启动Sink</button>
                        <button class="btn btn-danger mb-3 ms-2" id="stopMqttSinkBtn" disabled
                            onclick="stopMqttSink()"><i class="fa-solid fa-circle-stop"></i>停止Sink</button>
                        <button class="btn btn-info mb-3 ms-2" id="querySinkTarget"
                            onclick="querySinkTarget()">查询目标表</button>
                        <div class="message-container p-3 border rounded">
                            <div id="flinkOutput" class="message-body"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 订单表单模态框 -->
    <div class="modal fade" id="orderModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modalTitle">订单信息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="orderForm">
                        <input type="hidden" id="orderId">
                        <div class="mb-3">
                            <label class="form-label">订单ID</label>
                            <input type="number" class="form-control" id="id" required>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">事件时间</label>
                            <input type="text" class="form-control" id="eventTime">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">产品ID</label>
                            <input type="number" class="form-control" id="productId">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">分类代码</label>
                            <input type="text" class="form-control" id="categoryCode">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">品牌</label>
                            <input type="text" class="form-control" id="brand">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">价格</label>
                            <input type="number" class="form-control" id="price">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitOrderForm()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirmModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>确定要删除这个订单吗？</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDelete"
                        onclick="onClickConfirmDelete()">删除</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 同步数量输入模态框 -->
    <div class="modal fade" id="syncCountModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">输入发送数量</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="syncCount" class="form-label">请输入发送订单页数</label>
                        <input type="number" class="form-control" id="syncCount" min="1" value="1">
                    </div>
                    <div class="mb-3">
                        <label for="pageSize" class="form-label">每页记录数</label>
                        <input type="number" class="form-control" id="pageSize" min="1" value="10">
                    </div>
                    <div class="mb-3 form-check">
                        <input type="checkbox" class="form-check-input" id="sendSocket">
                        <label class="form-check-label" for="sendSocket">是否发送WebSocket消息</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="confirmSync"
                        onclick="onClickConfirmSync()">确定</button>
                </div>
            </div>
        </div>
    </div>
</body>

<script src="/js/jquery-3.7.1.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
<script src="/js/bootstrap-table.min.js"></script>
<script src="/js/jquery-confirm.min.js"></script>
<script src="/js/pub.js"></script>
<script src="/js/task.js"></script>
<script src="/js/order.js"></script>
<script src="/js/mqtt.js"></script>
<script src="/js/font-awesome-all.min.js" data-auto-replace-svg="nest"></script>
<!-- <script th:inline="javascript"> -->
<script>
    var currentDeleteId = null;
    // 操作列格式化
    function operateFormatter(value, row, index) {
        return [
            '<button class="btn btn-sm btn-primary" onclick="editOrder(' + row.id + ')">编辑</button>',
            '<button class="btn btn-sm btn-danger" onclick="deleteOrder(' + row.id + ')">删除</button>'
        ].join(' ');
    }

    // 初始化表格
    function ajaxQueryPage(params) {
        const pageNo = params.data.offset / params.data.limit + 1;
        const pageSize = params.data.limit;
        const url = `/orders/query?pageNo=${pageNo}&pageSize=${pageSize}`;
        let _data = JSON.stringify({
            categoryCode: $('#queryCategoryCode').val(),
            brand: $('#queryBrand').val(),
            zoneName: $('#queryZone').val()
        });

        $.ajax({
            url: url,
            type: "POST",
            headers: {
                "auth2045": getLoginToken()
            },
            contentType: "application/json",
            async: true,
            data: _data,
            success: function (rs, status, xhr) {
                params.success({ //注意，必须返回参数 params
                    "total": rs.total,
                    "rows": rs.rows
                },
                    "ok", //这个好像暂时没有用到
                    xhr
                );
            },
            error: function (jqXHR, textStatus, errorThrown) {
                alert({
                    title: '警告',
                    content: "查询失败，网络错误:" + textStatus,
                    autoClose: 'ok|500'
                });
                params.success({ //注意，必须返回参数 params
                    "total": 0,
                    "rows": []
                },
                    "ok", //这个好像暂时没有用到
                    jqXHR
                );
            }
        });
    }

    // 显示添加表单
    function showAddForm() {
        document.getElementById('modalTitle').textContent = '添加订单';
        document.getElementById('orderForm').reset();
        document.getElementById('orderId').value = '';
        const modal = new bootstrap.Modal(document.getElementById('orderModal'));
        modal.show();
    }

    // 提交订单表单
    function submitOrderForm() {
        const order = {
            id: document.getElementById('id').value,
            eventTime: document.getElementById('eventTime').value,
            productId: document.getElementById('productId').value,
            categoryCode: document.getElementById('categoryCode').value,
            brand: document.getElementById('brand').value,
            price: document.getElementById('price').value
        };

        const url = '/orders/save';

        fetch(url, {
            method: "POST",
            headers: {
                'Content-Type': 'application/json',
                "auth2045": getLoginToken()
            },
            body: JSON.stringify(order)
        })
            .then(() => {
                const modal = bootstrap.Modal.getInstance(document.getElementById('orderModal'));
                modal.hide();
                queryOrders();
            });
    }

    // 编辑订单
    function editOrder(id) {
        fetch(`/orders/queryById?id=${id}`, {
            method: 'GET',
            headers: {
                "auth2045": getLoginToken()
            }
        })
            .then(response => response.json())
            .then(order => {
                document.getElementById('modalTitle').textContent = '编辑订单';
                document.getElementById('orderId').value = order.id;
                document.getElementById('id').value = order.id;
                document.getElementById('eventTime').value = order.eventTime || '';
                document.getElementById('productId').value = order.productId || '';
                document.getElementById('categoryCode').value = order.categoryCode || '';
                document.getElementById('brand').value = order.brand || '';
                document.getElementById('price').value = order.price || '';
                const modal = new bootstrap.Modal(document.getElementById('orderModal'));
                modal.show();
            });
    }

    // 删除订单
    function deleteOrder(id) {
        currentDeleteId = id;
        const modal = new bootstrap.Modal(document.getElementById('confirmModal'));
        modal.show();
    }

    // 确认删除
    function onClickConfirmDelete() {
        if (currentDeleteId) {
            fetch(`/orders/delete?id=${currentDeleteId}`, {
                method: 'POST',
                headers: {
                    "auth2045": getLoginToken()
                }
            })
                .then(() => {
                    queryOrders();
                    const modal = bootstrap.Modal.getInstance(document.getElementById('confirmModal'));
                    modal.hide();
                });
        }
    }

    // 查询订单
    function queryOrders() {
        $('#orderTable').bootstrapTable('refresh');
    }

    // WebSocket连接
    function initWebSocket() {
        if (!window.order) {
            window.order = {};
        }
        if (window.order.wsUri === undefined || window.order.wsUri === null) {
            window.order.wsUri = getWebsocketUri();
        }
        if (window.order.Websocket == undefined || window.order.Websocket == null) {
            window.order.websocket = null;
        }
        if (window.order.websocket != undefined && window.order.websocket != null) {
            console.log("WebSocket已存在，无需初始化");
            return;
        }
        console.log("初始化websocket连接");
        let websocket = new WebSocket(window.order.wsUri);
        websocket.onopen = function (evt) {
            addMessageToWebsocketOut("WebSocket连接已建立");
            //发送消息给服务器，告诉自己的名称
            websocket.send("setName:" + FLINK_TEST_FROMMQTT_SINKTOJDBC);
        };
        websocket.onclose = function (evt) {
            if (window.order.websocket != null) {
                //关闭websocket连接
                window.order.websocket.close();
                clearInterval(window.order.websocketHeartbeatInterval);
                window.order.websocket = null;
                addMessageToWebsocketOut("关闭webSocket");
            }
            // 启用重连按钮
            document.getElementById('restartWebsocket').disabled = false;
        };
        websocket.onmessage = function (evt) {
            let data = JSON.parse(evt.data);
            if (data.stageType === MESSAGE_STAGE_TYPE_JOB_ISFINISHED) {
                //此处必须延迟一秒，否则可能就算是可以重用，也会被另外一个操作覆盖。
                setTimeout(() => {
                    document.getElementById('startMqttBtn').disabled = false;
                }, 1000);
            }

            if (data.receiver == undefined || data.receiver == "") {
                addMessageToWebsocketOut(data.data);
            }
            else {
                addMessageToFlinkOut(data.data);
            }


        };
        websocket.onerror = function (evt) {
            // 启用重连按钮
            addMessageToWebsocketOut("WebSocket错误: " + evt);
            if (window.order.websocket != null) {
                //关闭websocket连接
                window.order.websocket.close();
                clearInterval(window.order.websocketHeartbeatInterval);
                window.order.websocket = null;
                addMessageToWebsocketOut("关闭webSocket");
            }
            document.getElementById('restartWebsocket').disabled = false;
        };
        window.order.websocket = websocket;

        // 每5秒发送一次心跳
        window.order.websocketHeartbeatInterval = setInterval(sendHeartbeat, 5000);
        //充值按钮状态
        document.getElementById('startMqttBtn').disabled = false;
        document.getElementById('restartWebsocket').disabled = true;
    }



    function onClickReleaseLock() {
        releaseLock(function () {
            document.getElementById("startMqttBtn").disabled = false;
        })
    }

    function onClickRestartWebsocket() {
        initWebSocket();
    }

    function onClickStartMqtt() {
        const syncModal = new bootstrap.Modal(document.getElementById('syncCountModal'));
        syncModal.show();
    }

    // 确认同步按钮点击事件
    function onClickConfirmSync() {
        const syncCount = document.getElementById('syncCount').value;
        if (!syncCount || syncCount < 1) {
            alert('请输入有效的同步数量');
            return;
        }

        const syncModal = bootstrap.Modal.getInstance(document.getElementById('syncCountModal'));
        syncModal.hide();

        const pageSize = document.getElementById('pageSize').value;
        const sendSocket = document.getElementById('sendSocket').checked ? 1 : 0;

        // 使用URLSearchParams构建URL参数
        const params = new URLSearchParams();
        params.append('pageQty', syncCount);
        params.append('pageSize', pageSize);
        params.append('sendSocket', sendSocket);
        params.append('testNo', FLINK_TEST_FROMMQTT_SINKTOJDBC);

        // 使用task.js中的sendToMqtt发送数据
        sendToMqtt(params, function () {
            document.getElementById('startMqttBtn').disabled = true;
        });
    }

    // MQTT Sink按钮点击事件
    function startMqttSink() {
        runTask(FLINK_TEST_FROMMQTT_SINKTOJDBC, function () {
            document.getElementById("startMqttSinkBtn").disabled = true;
            document.getElementById("stopMqttSinkBtn").disabled = false;
        }, {});
    }
    // 停止JDBC Sink按钮点击事件
    function stopMqttSink() {
        stopMqttTask(FLINK_TEST_FROMMQTT_SINKTOJDBC, function (result) {
            if (result.data) {
                document.getElementById("startMqttSinkBtn").disabled = false;
                document.getElementById("stopMqttSinkBtn").disabled = true;
            }
        });
    }

    // 查询目标表
    function querySinkTarget() {
        fetch('/orders/countTargetOrder', {
            method: 'GET',
            headers: {
                "auth2045": getLoginToken()
            }
        })
            .then(response => response.json())
            .then(data => {
                addMessageToFlinkOut("目标表累计收到数据:" + data.data + "条");
            });
    }

    // 发送心跳消息
    function sendHeartbeat() {
        if (window.order.websocket && window.order.websocket.readyState === WebSocket.OPEN) {
            window.order.websocket.send("heartbeat");
        } else {
            console.log("WebSocket未连接，无法发送心跳");
        }
    }

    // 初始化WebSocket连接和心跳定时器
    $(document).ready(function () {
        initWebSocket();
        setButtonStatus();
    });

    window.addEventListener("unload", function (event) {
        if (window.order.websocketHeartbeatInterval) {
            clearInterval(window.order.websocketHeartbeatInterval);
            console.log('已清理心跳定时器');
        }
        if (window.order.websocket) {
            window.order.websocket.close();
            console.log('已关闭WebSocket连接');
        }
        stopMqttSink();
    });

    

</script>

</html>